package com.kissoft.common.util;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class KisUtil {

    private static KisUtil singleton = null;
	final static Logger logger = Logger.getRootLogger();
    
    public KisUtil(){}
    public static KisUtil getInstance(){
		if(singleton == null) singleton = new KisUtil();
        return singleton;
	}

    public Cookie makeCookis(String key, String value, Integer hour){
    	Cookie cookie = new Cookie(key, value);
    	cookie.setMaxAge(60*60*hour);
    	cookie.setPath("/");
    	return cookie;
    }
    
    public String getCookie(String key, Cookie[] cookies){
    	
    	String rtnValue = "";
    	
    	if(cookies != null){
        	for (int i = 0; i < cookies.length; i++) {
        		if(cookies[i].getName().equals(key)){
        			rtnValue =  cookies[i].getValue();
        			break;
        		}
        	}    		
    	}
    	
    	return rtnValue;
    }
    
	public int delFile(String filename){

		int result = 0;
		File file = new File(filename);
		
		if(file.exists()){
			if(file.isFile()){
				file.delete();
				result = 1;	
			}
		}	
		return result;
	}
	
	/**
	 * 폴더 존재 유무를 파악하고 없으면 생성한다.
	 * @param folder
	 * @return
	 * @throws IOException
	 */
	public boolean chkFolder(String folder) throws IOException{
		boolean result = false;
		
		File file = new File(folder);
		
		if(!file.isDirectory()){
			return file.mkdir();
		}else{
			result = true;
			return result;	
		}
				
	}
	public boolean delFolder(String folder){
		boolean result = false;
		
		File file = new File(folder);
		
		if(file.isDirectory()){
			File[] childFile = file.listFiles();
			int size = childFile.length;
			boolean confirm = false;
			for(int i=0; i<size; i++){
				if(childFile[i].isFile()){
					confirm = childFile[i].delete();
					logger.debug("파일 삭제 " + childFile[i] + " : " + confirm);	
				}
			}
			return file.delete();
		}else{
			result = true;
			return result;	
		}		
	}

     public void copyDirectory(java.io.File srcDir, java.io.File dstDir) throws java.io.IOException {
        if (srcDir.isDirectory()) {
            if (!dstDir.exists()) {
                dstDir.mkdir();
            }

            String[] children = srcDir.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new java.io.File(srcDir, children[i]),
                                     new java.io.File(dstDir, children[i]));
            }
        } else {
            // This method is implemented in e1071 Copying a File
            copyFile(srcDir, dstDir);
        }
    }
    // Copies src file to dst file.
    // If the dst file does not exist, it is created
    public void copyFile(java.io.File src, java.io.File dst) throws java.io.IOException {
        java.io.InputStream in = new java.io.FileInputStream(src);
        java.io.OutputStream out = new java.io.FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
    
	public String getReq (HttpServletRequest request, String param, String def){
		  if (request.getParameter(param) == null || request.getParameter(param).equals(""))   return def;
		  else  return (String)request.getParameter(param);
		}    
	
	/**
	 * Request로 넘어온 값이 널 또는 공백인지 확인 해서 온전한 값이면 그대로 리턴 값이 널또는 공백이면 def로 반환한다.
	 * @param param
	 * @param def
	 * @return
	 */	
	public String getNullChk (String param, String def){
		  if (param == null || param.equals(""))   return def;
		  else  return param;
		}
	
	/**
	 * Request로 넘어온 값이 널 또는 공백인지 확인 해서 온전한 값이면 그대로 리턴 값이 널또는 공백이면 def로 반환한다.
	 * @param param
	 * @param def
	 * @return
	 */
	public int getNullChk (Integer param, int def){
		  if (param == null)   return def;
		  else  return param;
		}	
	
	/**
	 * 문자열 치환
	 * @param line
	 * @param oldString
	 * @param newString
	 * @return
	 */
	public String replace(String line, String oldString, String newString){
		   for(int index = 0; (index = line.indexOf(oldString, index)) >= 0; index += newString.length())
		       line = line.substring(0, index) + newString + line.substring(index + oldString.length());
		   return line;
		}
	
	public String chkDupFile(String path, String filename){

		String rtnValue = filename;
		
		File newFile = new File(path, filename);
		if (newFile.exists()){ 
			String filehead, filetail,tempfile;
			for (int i_du = 0; true; i_du++) { // a(0).gif, a(1).gif
				
				if(filename.indexOf(".") != -1){
					filehead = filename.substring(0, filename.lastIndexOf("."));
					filetail = filename.substring(filename.lastIndexOf(".")+1,filename.length() );
					newFile = new File(path, filehead + "(" + i_du + ")."+ filetail);// (0)a.gif,(1)a.gif
					tempfile = filehead + "(" + i_du + ")."+ filetail;
				}else{
					newFile = new File(path, filename + "(" + i_du + ")");// (0)a.gif,(1)a.gif
					tempfile = filename + "(" + i_du + ")";
				}
				if (!newFile.exists()){
					filename = tempfile;
					break;
				}
			}
		  }		
		rtnValue = filename;
		
		return rtnValue;
	}
	
}

